package org.karelun.rabbit.server;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.cdo.server.CDOServerUtil;
import org.eclipse.emf.cdo.server.IRepository;
import org.eclipse.emf.cdo.server.IStore;
import org.eclipse.emf.cdo.server.db.CDODBUtil;
import org.eclipse.emf.cdo.server.db.mapping.IMappingStrategy;
import org.eclipse.emf.cdo.server.net4j.CDONet4jServerUtil;
import org.eclipse.net4j.acceptor.IAcceptor;
import org.eclipse.net4j.db.DBUtil;
import org.eclipse.net4j.db.IDBAdapter;
import org.eclipse.net4j.db.IDBConnectionProvider;
import org.eclipse.net4j.db.h2.H2Adapter;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.OMBundle;
import org.eclipse.net4j.util.om.OMPlatform;
import org.eclipse.net4j.util.om.OSGiActivator;
import org.eclipse.net4j.util.om.log.OMLogger;
import org.h2.jdbcx.JdbcDataSource;

public abstract class OM {

	public static final String BUNDLE_ID = "org.karelun.rabbit.server";

	public static final OMBundle BUNDLE = OMPlatform.INSTANCE.bundle(BUNDLE_ID,
			OM.class);

	public static final OMLogger LOG = BUNDLE.logger();

	private static IRepository repository;

	private static IAcceptor acceptor;

	public static final class Activator extends OSGiActivator {

		public Activator() {
			super(BUNDLE);
		}

		@Override
		protected void doStart() throws Exception {
			OM.LOG.info("Rabbit server starting");
			String dir = System.getProperty("user.home");
			String databasePath=dir+"/databse/rabbit";
			JdbcDataSource dataSource = new JdbcDataSource();
			dataSource.setURL("jdbc:h2:"+databasePath);

			IMappingStrategy mappingStrategy = CDODBUtil
					.createHorizontalMappingStrategy(true);
			IDBAdapter dbAdapter = new H2Adapter();
			IDBConnectionProvider dbConnectionProvider = DBUtil
					.createConnectionProvider(dataSource);
			IStore store = CDODBUtil.createStore(mappingStrategy, dbAdapter,
					dbConnectionProvider);

			Map<String, String> props = new HashMap<String, String>();
			props.put(IRepository.Props.OVERRIDE_UUID, "rabbit");
			props.put(IRepository.Props.SUPPORTING_AUDITS, "true");
			props.put(IRepository.Props.SUPPORTING_BRANCHES, "false");

			repository = CDOServerUtil.createRepository("rabbit", store, props);
			CDOServerUtil.addRepository(IPluginContainer.INSTANCE, repository);
			CDONet4jServerUtil.prepareContainer(IPluginContainer.INSTANCE);

			String description = "0.0.0.0:" + 2036;
			acceptor = (IAcceptor) IPluginContainer.INSTANCE.getElement(
					"org.eclipse.net4j.acceptors", "tcp", description);
			OM.LOG.info("Rabbit server started");
		}

		@Override
		protected void doStop() throws Exception {
			OM.LOG.info("Rabbit server stopping");
			LifecycleUtil.deactivate(acceptor);
			LifecycleUtil.deactivate(repository);
			OM.LOG.info("Gastro server stopped");
		}
	}
}
